package top.lyf1210.yuwenpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.lyf1210.yuwenpicturebackend.exception.BusinessException;
import top.lyf1210.yuwenpicturebackend.exception.ErrorCode;
import top.lyf1210.yuwenpicturebackend.exception.ThrowUtils;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

import static top.lyf1210.yuwenpicturebackend.constant.FileConstant.*;
import static top.lyf1210.yuwenpicturebackend.constant.FileConstant.FILE_SIZE_ERROR;

/**
 * @ClassNameUrlPictureUpload
 * @Description TODO
 * @Author钰玟
 * @Date2025/5/9 下午4:47
 * @Version 1.0
 **/
@Service
@Slf4j
public class UrlPictureUpload extends PictureUploadTemplate{
    @Override
    protected void validPicture(Object inputSource) {
        String imageUrl = (String) inputSource;


        //1. 判断url是否为空
        ThrowUtils.throwIf(StrUtil.isBlank(imageUrl), ErrorCode.PARAMS_ERROR,URL_CAN_NOT_BE_NULL);
        //2. 验证url格式
        try{
            new URL(imageUrl);
        } catch (MalformedURLException e) {
            log.error("url 格式错误",e);
            throw new BusinessException(ErrorCode.PARAMS_ERROR,URL_TOO_LONG);
        }
        //3. 验证url的协议
        ThrowUtils.throwIf(!(imageUrl.startsWith("http")|| imageUrl.startsWith("https")),ErrorCode.PARAMS_ERROR,URL_PROTOCOL);
        //4. 验证图片类型
        //4.1 获取图片 使用 Header请求方法
        HttpResponse response = null;
        try {
            //4.2 请求图片
            response = HttpUtil.createRequest(Method.HEAD, imageUrl).execute();
            if(response.getStatus() != HttpStatus.HTTP_OK){
                return ;
            }
            //4.3  获取图片类型 CONTENT_TYPE
            String contentType = response.header(Header.CONTENT_TYPE);
            if(StrUtil.isNotBlank(contentType)){
                //允许图片的类型
                final List<String> ALLOW_FILE_TYPE = Arrays.asList("image/jpeg", "image/png", "image/jpg","image/webp");
                ThrowUtils.throwIf(!ALLOW_FILE_TYPE.contains(contentType.toLowerCase()),ErrorCode.PARAMS_ERROR,FILE_TYPE_ERROR);
            }
            //5.检验文件大小
            //5.1 获取文件大小 CONTENT_LENGTH
            String contentLength = response.header(Header.CONTENT_LENGTH);
            if(StrUtil.isNotBlank(contentLength)){
                try{
                    // 5.2 转换为long
                    long fileLength = Long.parseLong(contentLength);
                    ThrowUtils.throwIf(fileLength>TWO_M,ErrorCode.PARAMS_ERROR,FILE_SIZE_ERROR);
                }catch (NumberFormatException e){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,FILE_SIZE_ERROR);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if(response!=null){
                response.close();
            }
        }
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String imageUrl = (String) inputSource;
        return FileUtil.getName(imageUrl);
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        String imageUrl = (String) inputSource;
        HttpUtil.downloadFile(imageUrl,file);
    }
}
